import base64
import json
import re

import requests

# OpenAI API Key
api_key = "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"

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')


def get_json_from_gpt(text):
    # 正则表达式模式，匹配被 <tag> 和 </tag> 包裹的内容
    pattern = re.compile(r'```json(.*?)```', re.DOTALL)
    # 查找所有匹配项
    matches = pattern.findall(text)
    # 打印提取到的内容
    list = []
    for match in matches:
        content = match.strip()
        list.append(json.loads(content))
    return list

def get_calorie_by_gpt():
    # Path to your image
    # image_path = "/Users/zhengyunwang/Downloads/lunch.jpg"
    image_path = "/Users/zhengyunwang/Downloads/早餐1.jpg"

    # Getting the base64 string
    base64_image = encode_image(image_path)
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    payload = {
        "model": "gpt-4o",
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        # "text":"请告诉我这份食物有哪些成分，分别有多少重量，以及每种成分所含有的碳水,脂肪，糖类，并把结果用json格式化后告诉我，我只需要格式化后的内容"
                        # "text": "这是我的午餐所吃的食物，请告诉我它们大概还有多少卡路里,用英文回复我，并把结果用json格式化后告诉我，我只需要格式化后的内容"
                        # "text": "这是我的午餐所吃的食物，请告诉我它们大概还有多少卡路里,请用英语告诉我结果，并把结果用json格式化后告诉我，我只需要格式化后的内容"
                        "text": "这是的一顿饭，请分析有多少种食物，还有含有energy，grains，vegetables，fruits，dairy，meats，nuts，fats，分别是多少份和多少克，只分析这几种类别，并把结果用json格式化后告诉我，我只需要格式化后的内容"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        }
                    }



                ]
            }
        ],
        "max_tokens": 300
    }
    response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
    print(response)

    raw_content = response.json()['choices'][0]['message']['content']
    print(raw_content)
    print("核心有价值的内容-------------------")
    print(get_json_from_gpt(raw_content))

if __name__ == '__main__':
    get_calorie_by_gpt()
